package com.it.ems.controller;

import com.it.ems.entity.User;
import com.it.ems.entity.Address;
import com.it.ems.service.UserService;
import com.it.ems.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/profile")
@PreAuthorize("isAuthenticated()") // 只有已认证的用户才能访问个人资料页面
public class ProfileController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private AddressService addressService;

    @GetMapping
    public String viewProfile(Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);
        
        if (currentUser == null) {
            return "redirect:/login";
        }
        
        // 获取用户的地址列表
        List<Address> addresses = addressService.findByUserId(currentUser.getId());
        
        model.addAttribute("user", currentUser);
        model.addAttribute("addresses", addresses);
        return "profile"; // 返回 profile.html 模板
    }

    @PostMapping("/update")
    @ResponseBody
    public ResponseEntity<?> updateProfile(@RequestBody User updatedUser) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);

        if (currentUser == null || !currentUser.getId().equals(updatedUser.getId())) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权修改他人资料"));
        }

        try {
            boolean usernameChanged = false;
            // 检查用户名是否被其他用户使用
            if (!currentUser.getUsername().equals(updatedUser.getUsername())) {
                User existingUser = userService.findByUsername(updatedUser.getUsername());
                if (existingUser != null && !existingUser.getId().equals(currentUser.getId())) {
                    return ResponseEntity.badRequest().body(Map.of("success", false, "message", "用户名已被使用，请选择其他用户名"));
                }
                usernameChanged = true;
            }
            
            // 只更新允许修改的字段
            currentUser.setPhoneNumber(updatedUser.getPhoneNumber());
            currentUser.setRealName(updatedUser.getRealName());
            currentUser.setUsername(updatedUser.getUsername());

            userService.updateProfile(currentUser);
            
            String message = usernameChanged ? "个人资料更新成功！用户名已更改" : "个人资料更新成功";
            return ResponseEntity.ok(Map.of("success", true, "message", message, "usernameChanged", usernameChanged));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("success", false, "message", "更新失败: " + e.getMessage()));
        }
    }

    @PostMapping("/change-password")
    @ResponseBody
    public ResponseEntity<?> changePassword(@RequestBody Map<String, String> request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);

        String oldPassword = request.get("oldPassword");
        String newPassword = request.get("newPassword");
        String confirmNewPassword = request.get("confirmNewPassword");

        if (currentUser == null) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "用户未登录"));
        }

        if (!newPassword.equals(confirmNewPassword)) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "两次输入的新密码不一致"));
        }

        try {
            userService.changePassword(currentUser.getId(), oldPassword, newPassword);
            return ResponseEntity.ok(Map.of("success", true, "message", "密码修改成功"));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("success", false, "message", e.getMessage()));
        }
    }
    
    // 地址管理接口
    @PostMapping("/address/add")
    @ResponseBody
    public ResponseEntity<?> addAddress(@RequestBody Address address) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);

        if (currentUser == null) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "用户未登录"));
        }

        // 检查用户地址数量限制
        List<Address> existingAddresses = addressService.findByUserId(currentUser.getId());
        if (existingAddresses.size() >= 5) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "最多只能添加5个地址"));
        }

        try {
            address.setUserId(currentUser.getId());
            address.setCreatedAt(LocalDateTime.now());
            address.setUpdatedAt(LocalDateTime.now());
            
            // 如果这是第一个地址或者用户设置为默认，则处理默认地址逻辑
            if (existingAddresses.isEmpty() || (address.getIsDefault() != null && address.getIsDefault())) {
                // 如果设为默认，先取消其他地址的默认状态
                if (address.getIsDefault() != null && address.getIsDefault()) {
                    for (Address existingAddr : existingAddresses) {
                        if (existingAddr.getIsDefault() != null && existingAddr.getIsDefault()) {
                            existingAddr.setIsDefault(false);
                            addressService.update(existingAddr);
                        }
                    }
                } else if (existingAddresses.isEmpty()) {
                    // 如果是第一个地址，自动设为默认
                    address.setIsDefault(true);
                }
            } else {
                // 确保不为null
                if (address.getIsDefault() == null) {
                    address.setIsDefault(false);
                }
            }

            addressService.save(address);
            return ResponseEntity.ok(Map.of("success", true, "message", "地址添加成功"));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("success", false, "message", "添加地址失败: " + e.getMessage()));
        }
    }

    @PostMapping("/address/update")
    @ResponseBody
    public ResponseEntity<?> updateAddress(@RequestBody Address address) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);

        if (currentUser == null) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "用户未登录"));
        }

        // 验证地址属于当前用户
        Address existingAddress = addressService.findById(address.getId());
        if (existingAddress == null || !existingAddress.getUserId().equals(currentUser.getId())) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权修改此地址"));
        }

        try {
            address.setUserId(currentUser.getId());
            address.setUpdatedAt(LocalDateTime.now());
            
            // 如果设置为默认地址，取消其他地址的默认状态
            if (address.getIsDefault()) {
                List<Address> userAddresses = addressService.findByUserId(currentUser.getId());
                for (Address addr : userAddresses) {
                    if (!addr.getId().equals(address.getId()) && addr.getIsDefault()) {
                        addr.setIsDefault(false);
                        addressService.update(addr);
                    }
                }
            }

            addressService.update(address);
            return ResponseEntity.ok(Map.of("success", true, "message", "地址更新成功"));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("success", false, "message", "更新地址失败: " + e.getMessage()));
        }
    }

    @PostMapping("/address/delete/{id}")
    @ResponseBody
    public ResponseEntity<?> deleteAddress(@PathVariable Long id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);

        if (currentUser == null) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "用户未登录"));
        }

        // 验证地址属于当前用户
        Address address = addressService.findById(id);
        if (address == null || !address.getUserId().equals(currentUser.getId())) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权删除此地址"));
        }

        try {
            boolean wasDefault = address.getIsDefault();
            addressService.delete(id);
            
            // 如果删除的是默认地址，设置第一个地址为默认
            if (wasDefault) {
                List<Address> remainingAddresses = addressService.findByUserId(currentUser.getId());
                if (!remainingAddresses.isEmpty()) {
                    Address firstAddress = remainingAddresses.get(0);
                    firstAddress.setIsDefault(true);
                    addressService.update(firstAddress);
                }
            }
            
            return ResponseEntity.ok(Map.of("success", true, "message", "地址删除成功"));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("success", false, "message", "删除地址失败: " + e.getMessage()));
        }
    }

    @PostMapping("/address/set-default/{id}")
    @ResponseBody
    public ResponseEntity<?> setDefaultAddress(@PathVariable Long id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);

        if (currentUser == null) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "用户未登录"));
        }

        // 验证地址属于当前用户
        Address address = addressService.findById(id);
        if (address == null || !address.getUserId().equals(currentUser.getId())) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权修改此地址"));
        }

        try {
            // 取消其他地址的默认状态
            List<Address> userAddresses = addressService.findByUserId(currentUser.getId());
            for (Address addr : userAddresses) {
                if (addr.getIsDefault()) {
                    addr.setIsDefault(false);
                    addressService.update(addr);
                }
            }
            
            // 设置当前地址为默认
            address.setIsDefault(true);
            addressService.update(address);
            
            return ResponseEntity.ok(Map.of("success", true, "message", "默认地址设置成功"));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("success", false, "message", "设置默认地址失败: " + e.getMessage()));
        }
    }
} 